package com.icss.mqsp.quartz.util;

import com.icss.mqsp.config.PropertyConfig;
import com.icss.pangu.logging.Log;
import com.icss.pangu.logging.LogFactory;
import com.icss.pangu.util.date.DateUtil;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CacheUtil
{
  private static Log log = LogFactory.getLog(CacheUtil.class);
  public static String lastJudgeTime = null;
  public static String updateTime = null;
  public static String lastCacheTime = null;
  private static Object obj = new Object();
  private static String ratDir = "rat";
  private static String ratAutoDir = "rat_auto";
  
  public static String getRatDir()
  {
    return ratDir;
  }
  
  public static void setRatDir(String ratDir)
  {
    ratDir = ratDir;
  }
  
  public static String getRatAutoDir()
  {
    return ratAutoDir;
  }
  
  public static void setRatAutoDir(String ratAutoDir)
  {
    ratAutoDir = ratAutoDir;
  }
  
  public static void cacheJudgment()
  {
    synchronized (obj)
    {
      if ((lastCacheTime == null) || (lastJudgeTime == null) || (checkTimeDif() > 30L) || (checkTimeDif() < 0L))
      {
        getUpdateTime();
        if ((updateTime != null) && (!updateTime.equals(lastCacheTime))) {
          cacheClean();
        } else {
          log.info("条件不符合,不进行缓存清除");
        }
        updateLastJudgeTime();
      }
      else
      {
        log.info("lastCacheTime=" + lastCacheTime + ",距离上次判断时间=" + checkTimeDif());
      }
    }
  }
  
  private static void cacheClean()
  {
    File f = new File(ratDir);
    if (!f.exists()) {
      f.mkdirs();
    }
    if ("1".equals(PropertyConfig.getInstance("system").getProperty("cache.autoCache")))
    {
      log.info("移动端自动缓存生成开始...");
      if (AutoCache.createDsCache())
      {
        log.info("移动端自动缓存生成成功...");
        coverOldCache();
      }
    }
    else
    {
      cleanOldRatCache();
      log.info("清除旧缓存成功...");
    }
    lastCacheTime = updateTime;
  }
  
  private static void cleanOldRatCache()
  {
    File file = new File(ratDir);
    if ((file.exists()) && 
      (file.isDirectory()))
    {
      File[] fs = file.listFiles();
      for (int m = 0; m < fs.length; m++) {
        if (fs[m].getName().indexOf(updateTime) == -1) {
          fs[m].delete();
        }
      }
    }
  }
  
  public static void copyFile(String originDirectory, String targetDirectory)
  {
    File origindirectory = new File(originDirectory);
    File targetdirectory = new File(targetDirectory);
    if ((!origindirectory.isDirectory()) || (!targetdirectory.isDirectory()))
    {
      log.info("不是正确的目录！");
      return;
    }
    File[] fileList = origindirectory.listFiles();
    for (File file : fileList) {
      if (file.isFile()) {
        try
        {
          FileInputStream fin = new FileInputStream(file);
          BufferedInputStream bin = new BufferedInputStream(fin);
          PrintStream pout = new PrintStream(targetdirectory
            .getAbsolutePath() + 
            "/" + file.getName());
          BufferedOutputStream bout = new BufferedOutputStream(pout);
          int total = bin.available();
          int count;
          while ((count = bin.available()) != 0)
          {
            int count1;
            int c = bin.read();
            bout.write((char)c);
          }
          bout.close();
          pout.close();
          bin.close();
          fin.close();
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
      }
    }
  }
  
  private static void deleteFile(File file)
  {
    if (file.isFile())
    {
      file.delete();
    }
    else if (file.exists())
    {
      File[] files = file.listFiles();
      for (int i = 0; i < files.length; i++)
      {
        log.info(files[i].getName());
        deleteFile(files[i]);
      }
      file.delete();
    }
  }
  
  private static void coverOldCache()
  {
    copyFile(ratAutoDir, ratDir);
    log.info("替换自动缓存文件夹文件到缓存文件夹成功");
    deleteFile(new File(ratAutoDir));
    log.info("删除自动缓存文件成功");
    cleanOldRatCache();
    log.info("删除缓存文件夹下旧的缓存文件成功");
  }
  
  public static synchronized long checkTimeDif()
  {
    SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
    Date d1 = null;
    Date d2 = null;
    long dif = -1L;
    try
    {
      d1 = f.parse(DateUtil.getCurrentDatetime());
      d2 = f.parse(lastJudgeTime);
      dif = (d1.getTime() - d2.getTime()) / 1000L / 60L;
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return dif;
  }
  
  public static void getUpdateTime()
  {
    log.info("getUpdataTime初始化");
    String tmpTime = getCurrentDate("yyyy-MM-dd");
    log.info("取得当前update时间：" + tmpTime);
    setUpdateTime(tmpTime);
    log.info("updateTime：" + updateTime);
    log.info("lastCacheTime:" + lastCacheTime);
  }
  
  public static String getCurrentDate(String format)
  {
    String defaultValue = null;
    Date dt = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    defaultValue = sdf.format(dt);
    return defaultValue;
  }
  
  private static void updateLastJudgeTime()
  {
    lastJudgeTime = DateUtil.getCurrentDatetime();
  }
  
  public static void setUpdateTime(String updateTime)
  {
    updateTime = updateTime;
  }
}
